package com.simen.usagestats;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.simen.absadapter.AbsAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    private ListView listView;
    private Button load;
    private UsageStatsManager usageStatsManager;
    private List<UsageEvents.Event> eventList = new ArrayList<>();
    private List<UsageStats> usageStatsList = new ArrayList<>();
    private int listType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list);
        load = (Button) findViewById(R.id.load);

        load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                load();
            }
        });

        Configuration con = getResources().getConfiguration();
        Log.d(TAG, "onCreate: " + con.mcc + " " + con.mnc);

        TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tel.getNetworkOperator();

        if (!TextUtils.isEmpty(networkOperator)) {
            int mcc = Integer.parseInt(networkOperator.substring(0, 3));
            int mnc = Integer.parseInt(networkOperator.substring(3));
            Log.d(TAG, "onCreate: " + mcc + " " + mnc);
        }
    }

    private void load() {
        if (check()) {
            if (usageStatsManager == null) {
                usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
            }

            if (listType == 0) {
                setTitle("queryEvents");
                UsageEvents usageEvents = usageStatsManager.queryEvents(System.currentTimeMillis() - 1000
                        * 60 * 60 * 24, System.currentTimeMillis());
                List<UsageEvents.Event> eventList = new ArrayList<UsageEvents.Event>();
                while (usageEvents.hasNextEvent()) {
                    UsageEvents.Event event = new UsageEvents.Event();
                    if (usageEvents.getNextEvent(event)) {
                        eventList.add(event);
                    }
                }
                Collections.reverse(eventList);
                this.eventList.clear();
                this.eventList.addAll(eventList);

                listView.setAdapter(new AbsAdapter<UsageEvents.Event>(MainActivity.this, this.eventList, R
                        .layout.layout_event) {
                    @Override
                    protected boolean onItemAdapter(AbsViewHolder viewHolder, UsageEvents.Event event, int position) {
                        viewHolder.setTextOrButton(R.id.packageName, event.getPackageName());
                        viewHolder.setTextOrButton(R.id.eventType, getEvent(event.getEventType()));
                        viewHolder.setTextOrButton(R.id.className, event.getClassName());
                        viewHolder.setTextOrButton(R.id.timeStamp, getTime(event.getTimeStamp()));
                        return false;
                    }
                });
            } else if (listType == 1) {
                setTitle("queryUsageStats");
                List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager
                        .INTERVAL_DAILY, System.currentTimeMillis() - 1000 * 60 * 60 * 24, System.currentTimeMillis());

                Collections.reverse(usageStatsList);
                this.usageStatsList.clear();
                this.usageStatsList.addAll(usageStatsList);

                listView.setAdapter(new AbsAdapter<UsageStats>(MainActivity.this, this.usageStatsList, R
                        .layout.layout_stats) {
                    @Override
                    protected boolean onItemAdapter(AbsViewHolder viewHolder, UsageStats usageStats, int position) {
                        viewHolder.setTextOrButton(R.id.packageName, usageStats.getPackageName());
                        viewHolder.setTextOrButton(R.id.lastUse, "最近使用:" + getTime(usageStats.getLastTimeUsed()));
                        viewHolder.setTextOrButton(R.id.totalTimeUse, "使用时长:" + getTotal(usageStats
                                .getTotalTimeInForeground()));
                        return false;
                    }
                });
            } else {
                listType = 0;
                load();
                return;
            }
            listType++;
        }
    }

    private boolean check() {
        if (!hasEnable()) {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivity(intent);
            return false;
        }
        return true;
    }

    /**
     * the user enabled my application
     *
     * @return
     */
    @SuppressLint("NewApi")
    private boolean hasEnable() {
        long ts = System.currentTimeMillis();
        UsageStatsManager usageStatsManager = (UsageStatsManager) getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                0, ts);
        if (queryUsageStats == null || queryUsageStats.isEmpty()) {
            return false;
        }
        return true;
    }

    private final static long HOUR = 3600000L;
    private final static long MINUTE = 60000L;

    private static String getTotal(long milliseconds) {
        int hour = (int) (milliseconds / HOUR);
        int minute = (int) ((milliseconds % HOUR) / MINUTE);
        return hour + "小时," + minute + "分钟";
    }

    private static String getTime(long milliseconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);
        return simpleDateFormat.format(calendar.getTime());
    }

    private static String getEvent(int eventType) {
        switch (eventType) {
            case UsageEvents.Event.MOVE_TO_BACKGROUND:
                return "进入后台服务";
            case UsageEvents.Event.MOVE_TO_FOREGROUND:
                return "进入前台";
            case UsageEvents.Event.NONE:
                return "No event type";
        }
        return "未知事件类型:" + eventType;
    }
}

//else if (listType == 2) {
//        setTitle("queryAndAggregateUsageStats");
//        Map<String, UsageStats> aggregateUsageStats = usageStatsManager.queryAndAggregateUsageStats(System
//        .currentTimeMillis() - 1000 * 60 * 60 * 24, System.currentTimeMillis());
//        }
